#include <time.h>

#include "Game.h"
#include "Terrain.h"
#include "BaseEntity.h"
#include "GameWorld.h"
#include "Enemy.h"


MSG Game::gameLoop()
{
	MSG msg;
	ZeroMemory( &msg, sizeof(msg) );
	gameWorld = new GameWorld();
	//worldMap = new WorldMap();
	//worldMap->LoadLevel("ugpTestMap.bsp");
	//worldMap->initWorldMap();

	clock_t timeNow = clock();
	clock_t timeThen = timeNow;
	double delta=(double)(timeNow - timeThen);
	deltaTime=200;
	isGO = false;

	gameWorld->loadSounds();

	gameWorld->checkSounds();

	gameWorld->playbckgrnd();

	while( msg.message!=WM_QUIT && isGO != true )
	{
		QueryPerformanceCounter(&timeStart);
		delta=(double)(timeNow - timeThen);
		delta = delta / 1000;
		// check for messages
		if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
		{
			TranslateMessage( &msg );
			DispatchMessage( &msg );
		}
		update(((float)delta));
		render();//Draw
		while(msg.message==NULL&&clock()<timeNow+300)
		{
			Sleep(1);
		}
		diMgr.getInput();//Get Input
		inputHandler();
		timeThen = timeNow;
        timeNow = clock();

		isGameOver();
		
		QueryPerformanceCounter(&timeEnd);
		deltaTime=(float)timeEnd.QuadPart -(float)timeStart.QuadPart;
 
	}

	gameWorld->releaseSounds();
	
	gameWorld->shutDown();

	return msg;
}

void Game::render()
{
	dxMgr.beginRender();

	//worldMap->Render();
	gameWorld->render();
	dxMgr.endRender(); 
}

void Game::inputHandler()
{
	gameWorld->WorldInput();
}

void Game::update(float a_dt)
{
	gameWorld->update(a_dt);
}

void Game::isGameOver()
{
	isGO = gameWorld->GameOver();
}

